#include "../include/SQL.h"
#include "../include/Db.h"

namespace ZY {

    SQL::SQL( string str )
    {
        sqlStr.assign( str );
    }

    SQL::~SQL()
    {

    }

    string SQL::getSQL( Db &db )
    {
        string str;
        str.assign( sqlStr );
        size_t index(0);

        vector<string>::iterator iter;

        int n;

        for( iter = args.begin() ; iter != args.end() ; iter ++ )
        {
            index = str.find_first_of( '?' , index );
            if ( index == string::npos ) {
                break;
            }
            char buff[(*iter).length() *3];

            n = mysql_real_escape_string( & db.link , buff , (*iter).c_str() , strlen( (*iter).c_str() ) );
            string strbuff("'");
            strbuff.append( buff,n );
            strbuff.append( "'" );

            str = str.replace( index , 1 , strbuff.c_str() , 0 , n + 2 );
            index ++;
        }

        return str;
    }

    vector<string> &SQL::getArgs()
    {
        return args;
    }

    SQL & SQL::addStringArg( const string &str )
    {
        args.push_back( str );

        return *this;
    }

    SQL & SQL::addIntArg( const int n )
    {
        char buff[16];
        int len;
        len = sprintf( buff , "%d" , n );
        string str( buff , len );
        return addStringArg( str );
    }

    SQL & SQL::addFloatArg( const float f )
    {
        char buff[32];
        int len;
        len = sprintf( buff , "%f" , f );
        string str( buff , len );
        return addStringArg( str );
    }

    SQL & SQL::addInt64Arg( const int64_t n )
    {
        char buff[64];
        int len;
        len = sprintf( buff , "%lld" , (long long int ) n );
        string str( buff , len );
        return addStringArg( str );
    }
}
